package com.lumberer.pay2021.wx.jsapi.payment.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.lumberer.pay2021.util.WxRequest;
import com.lumberer.pay2021.wx.init.config.MerchantConfig;
import com.lumberer.pay2021.wx.init.config.RequestURL;
import com.lumberer.pay2021.wx.jsapi.payment.entity.PayData;
import com.lumberer.pay2021.wx.jsapi.payment.entity.pay.JsApi;
import com.lumberer.pay2021.wx.jsapi.payment.entity.pay.amount.Amount;
import com.lumberer.pay2021.wx.jsapi.payment.entity.pay.payer.Payer;
import com.lumberer.pay2021.wx.jsapi.payment.service.JsApiService;
@Service
public class JsApiServiceImpl implements JsApiService{

	@Override
	public PayData transactions(JsApi data) {
		if(StringUtils.isEmpty(data.getAppid())){
			data.setAppid(MerchantConfig.appid);
		}
		if(StringUtils.isEmpty(data.getMchid())){
			data.setMchid(MerchantConfig.mchid);
		}
		if(StringUtils.isEmpty(data.getDescription())){
			throw new RuntimeException("商品描述未传入");
		}
		if(StringUtils.isEmpty(data.getOut_trade_no())){
			throw new RuntimeException("商户订单号未传入");
		}
		String NotifyUrl=data.getNotify_url();
		if(StringUtils.isEmpty(NotifyUrl)){
			throw new RuntimeException("通知地址未传入");
		}
		if(NotifyUrl.indexOf("http")==-1&&NotifyUrl.indexOf("HTTP")==-1&&NotifyUrl.indexOf("HTTPS")==-1&&NotifyUrl.indexOf("https")==-1){
			throw new RuntimeException("请传入带有HTTP或HTTPS的回调地址");
		}
		Amount amount=data.getAmount();
		if(null==amount.getTotal()){
			throw new RuntimeException("请传入订单金额信息-总金额");
		}
		if(StringUtils.isEmpty(amount.getCurrency())){
			throw new RuntimeException("请传入订单金额信息-货币类型");
		}
		Payer payer=data.getPayer();
		if(StringUtils.isEmpty(payer.getOpenid())){
			throw new RuntimeException("请传入支付者信息-用户标识");
		}
		//生成预支付订单
		JSONObject prepayResult = WxRequest.wxHttpPost(RequestURL.JSAPI, data);
		String prepayId=prepayResult.getString("prepay_id");
		if(StringUtils.isEmpty(prepayId)){
			throw new RuntimeException(prepayResult.toJSONString());
		}else{
			//进行数据签名，返回前端调用数据
			PayData payData=WxRequest.paySign(MerchantConfig.appid, prepayId, MerchantConfig.keyPath);
			return payData;	
			
		}
	}

}
